package by.demchenko.sample.dataaccess.impl;

import by.demchenko.sample.dataaccess.base.AccountDao;
import by.demchenko.sample.datamodel.Account;
import by.demchenko.sample.datamodel.Account_;
import org.springframework.stereotype.Repository;
import org.springframework.util.DigestUtils;

import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import java.util.List;

@Repository
public class AccountDaoImpl extends AbstractDaoImpl<Integer, Account> implements AccountDao {

    protected AccountDaoImpl() {
        super(Account.class);
    }


    @Override
    public Account getAccountByCredentials(String login, String password) {
        CriteriaBuilder cBuilder = getEm().getCriteriaBuilder();

        CriteriaQuery<Account> criteria = cBuilder.createQuery(Account.class);
        Root<Account> root = criteria.from(Account.class);
        criteria.select(root);

        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());

        root.fetch(Account_.person);
        criteria.distinct(true);

        criteria.where(
                cBuilder.and(
                        cBuilder.equal(
                                root.get(Account_.login), login),
                        cBuilder.equal(
                                root.get(Account_.password), md5Password)
                )
        );

        TypedQuery<Account> query = getEm().createQuery(criteria);
        Account result = null;
        try {
            result = query.getSingleResult();
        } catch (javax.persistence.NoResultException e) {
            return null;
        }

        return result;
    }

    @Override
    public boolean findLogin(String login) {
        CriteriaBuilder cBuilder = getEm().getCriteriaBuilder();

        CriteriaQuery<Account> criteria = cBuilder.createQuery(Account.class);
        Root<Account> root = criteria.from(Account.class);
        criteria.select(root);

        criteria.where(
                cBuilder.equal(
                        root.get(Account_.login), login)
        );

        TypedQuery<Account> query = getEm().createQuery(criteria);

        List<Account> list = query.getResultList();

        return (list.size() > 0);
    }


}